<template>
    <div class="mod-schedule"  style="padding: 20px 10px;">
      <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
        <el-form-item>
          <el-input v-model="dataForm.beanName" placeholder="库表名称" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="getDataList(1)">查询</el-button>
          <el-button  type="primary" @click="addOrUpdateHandle()">新增</el-button>
          <!-- <el-button  type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button> -->
        </el-form-item>
      </el-form>
      <el-table
        :data="dataList"
        border
        v-loading="dataListLoading"
        @selection-change="selectionChangeHandle"
        style="width: 100%;">
        <el-table-column
          type="selection"
          header-align="center"
          align="center"
          width="50">
        </el-table-column>
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="tableName"
          header-align="center"
          align="center"
          label="表名称">
        </el-table-column>
        <el-table-column
          prop="field"
          header-align="center"
          align="center"
          label="表字段">
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="180"
          label="操作">
          <template slot-scope="scope">
            <el-button  type="text" size="small" @click="addOrUpdateHandle(scope.row)">修改</el-button>
            <el-popconfirm title="确定删除吗？" icon-color="#f00" @confirm="deleteHandle(scope.row.id)">
                <el-button slot="reference" type="text" size="small">删除</el-button>
            </el-popconfirm>
            <el-button  type="text" size="small" @click="getDetile(scope.row)">查看数据</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;padding-top: 10px;">
        <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      </div>
      <!-- 弹窗, 新增 / 修改 -->
      <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
      <!-- 弹窗, 日志列表 -->
      <log v-if="logVisible" ref="log"></log>
      <el-dialog
          width="30%"
          title="JSON参数编辑"
          :visible.sync="editPostJsonFlag"
          append-to-body>
          <div v-if="editPostJsonFlag">
            <vue-json-editor
              v-model="resultInfo"
              :showBtns="false"
              :mode="'code'"
              @json-change="onJsonChange"
              @json-save="onJsonSave"
              @has-error="onError"
            />
            <br>
          <el-button type="primary" @click="checkJson">确定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        title=""
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        width="70%"
        :before-close="handleClose">
        <div style="margin-bottom: 20px;display: flex;flex-direction: row;justify-content: space-between;">
          <div>
           <div style="display: inline-block;vertical-align: top;">
            <el-upload
              class="upload-demo"
              ref="file"
              :data="dataObj"
              :action="baseUrl"
              :on-success="onsuccess"
              :on-change="onchange"
              :headers="headersObj"
              multiple>
              <el-button size="mini" type="primary">导入Excel</el-button>
            </el-upload>
           </div>
            <el-button size="small" type="primary" plain style="margin-left: 10px;" @click="inportJson">导入JSON</el-button>
            <el-button size="small" @click="vlogs">日志</el-button>
            <el-button type="danger" size="small" @click="clearData('all')">一键清空</el-button>
            <el-button type="danger" :disabled="multipleSelection.length==0" size="small" @click="clearData()">批量删除</el-button>
          </div>
          <span @click="addList" 
            style="cursor: pointer;border-radius: 100%;background: #17b3a3;color: #fff;font-size: 26px;width:26px;height:26px;text-align: center;line-height: 1;">
            +
          </span>
        </div>
        <el-table
        v-loading="tabLoading"
        :data="tableData"
        border
        :row-class-name="tabRowClassName"
        @cell-click="editCell"
        stripe
        @selection-change="handleSelectionChange"
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          v-for="(item,index) in tableKeys"
          align="center"
          :key="index"
          :prop="item"
          :label="item">
          <template slot-scope="scope">
            <div v-if="scope.row.isEdit">
                <el-input type="text" :disabled="item=='auto_id'" v-model="scope.row[item]"/>
            </div>
            <div v-else>
              {{scope.row[item]}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          v-if="tableData.length!=0"
          prop="操作"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="save([scope.row])">保存</el-button>
            <el-button type="text" v-if="scope.row.showDel" size="mini" @click="deleteData(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
        <div style="text-align: right;padding-top: 10px;">
          <el-pagination
          @size-change="sizeChangeHandle2"
          @current-change="currentChangeHandle2"
          :current-page="pageIndex2"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize2"
          :total="totalPage2"
          layout="total, sizes, prev, pager, next, jumper">
        </el-pagination>
      </div>

      <!-- 内部嵌套 -->


      <el-dialog
      width="50%"
      title="日志列表"
      :visible.sync="innerVisible"
      :close-on-click-modal="false"
      append-to-body>

      <el-table
        :data="tableData3"
        border
        style="width: 100%">
        <el-table-column
          v-for="(item,index) in tableKeys3"
          align="center"
          :key="index"
          :prop="item.key"
          :label="item.title">
          <template slot-scope="scope">
            <div style="width:180px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
              {{scope.row[item.key]}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          v-if="tableData3.length!=0"
          prop="操作"
          label="操作">
          <template slot-scope="scope">
            <el-button :disabled="scope.row.errorMessage?false:true" type="primary" size="mini" @click="redushEntry(scope.row.logId)">重新入库</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right;margin-top: 10px;">
        <el-pagination
        @size-change="sizeChangeHandle3"
        @current-change="currentChangeHandle3"
        :current-page="pageIndex3"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize3"
        :total="totalPage3"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      </div>
    </el-dialog>
      <!-- 内部嵌套 -->
        <!-- <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleFun(1)">取 消</el-button>
          <el-button type="primary" @click="dialogVisibleFun(2)">确 定</el-button>
        </span> -->
      </el-dialog>
    </div>
  </template>


<style>
  .el-upload-list{
    width:80px;
  }
</style>

  <script>
    import AddOrUpdate from './schedule-add-or-update'
    import Log from './schedule-log'
    import { getToken, setToken, removeToken } from '@/utils/auth'
    import vueJsonEditor from 'vue-json-editor'
    import request from '@/utils/request'
    export default {
      data () {
        return {
          tabLoading:false,
          hasJsonFlag:true,
          editPostJsonFlag:false,
          resultInfo:{id:"",dataList:[]},
          innerVisible:false,
          selectObj:null,
          dataObj:{},
          headersObj:{},
          dialogVisible:false,
          tableData:[],
          tableKeys:[],
          dataForm: {
            beanName: ''
          },
          dataList: [],
          selectDataId:"",
          pageIndex: 1,
          pageSize: 10,
          pageIndex2: 1,
          pageSize2: 10,
          totalPage2:0,

          pageIndex3: 1,
          pageSize3: 10,
          totalPage3:0,
          tableData3:[],
          tableKeys3:[],

          totalPage: 0,
          baseUrl:"",
          dataListLoading: false,
          dataListSelections: [],
          addOrUpdateVisible: false,
          logVisible: false,
          multipleSelection:[]
        }
      },
      components: {
        AddOrUpdate,
        vueJsonEditor,
        Log
      },
      created () {
        this.baseUrl = window.SITE_CONFIG['baseUrl']+"/table/config/importExcel"
        this.headersObj = {
          'token':getToken()
        }
        this.getDataList()
      },
      methods: {
        onJsonChange (value) {
            this.onJsonSave(value)
        },
      onError(value) {
         this.hasJsonFlag = false
      },
      //确定按钮 检查json
      checkJson(){
        if(this.hasJsonFlag){
          this.editPostJsonFlag = false
          this.save('SAVEJSON')
          return true
        }
      },
      // 输入值的时候调用
      onJsonSave (value) {
        this.resultInfo = JSON.parse(JSON.stringify(value))
        this.hasJsonFlag = true
      },
      inportJson(){
        this.resultInfo = {id:this.selectDataId,dataList:[]},
        this.editPostJsonFlag = true
      },
      dialogVisibleFun(v){
        if(v==1){
          this.dialogVisible = false
        }else{
          this.save(this.tableData)
        }
      },
      onchange(file,fileList){
        if(fileList.length>1){
          fileList.splice(0,1);
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      clearData(v){
        this.$confirm(`确定${v=='all'?'清空':'删除'}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let p = {
            id:this.selectDataId
          }
          if(v!='all'){
            let ids = []
            if(this.multipleSelection.length==0){
              this.$message.error('请先选择')
              return
            }else{
              this.multipleSelection.forEach((item,index)=>{
                ids.push(item.auto_id)
              })
            }
            p['idList'] = ids
          }
          request({
            url:"/ht-datadevelop/table/config/deleteAllDataByTableId",
            method: 'post',
            data:p
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success(v=='all'?'已清空':'已删除')
              this.getIdList()
            } else {
              this.$message.error(res.msg)
            }
          })
        }).catch(() => {})
      },
        redushEntry(v){
          request({
            url: '/ht-datadevelop/table/config/tableConfigLogAbnormalData',
            method: 'post',
            data:v
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message.error('入库成功')
              this.vlogs()
            } else {
             this.$message.error(data.msg)
            }
          })
        },
        vlogs(){
          this.innerVisible = true
          request({
            url: '/ht-datadevelop/table/config/tableConfigLogList',
            method: 'post',
            data:{
              table_name:this.selectObj.tableName,
              page:this.pageIndex3+"",
              limit:this.pageSize3+""
            }
          }).then(res => {
            if (res.code === 200) {
              this.tableKeys3 = [{key:"tableName",title:"表名"},{key:"logId",title:"日志ID"},{key:"sqlMessage",title:"sql语句"},{key:"errorMessage",title:"错误信息"}]
              this.tableData3 = res.data.list
              this.totalPage3 = res.data.totalCount

            } else {
              this.tableData3 = []
              this.totalPage3 = 0
            }
          })
        },
        onsuccess(v){
          if(v.code==0){
            this.getIdList()
          }else{
            this.$message.error(v.msg)
          }
        },
        deleteData(v){
          let i = -1
          let a = JSON.parse(JSON.stringify(this.tableData))
          a.forEach((item,index)=>{
            if(item.index==v.index){
              i = index
            }
          })
          a.splice(i,1)
          this.tableData = JSON.parse(JSON.stringify(a))
        },
        addList(){
          let obj = {}
          obj.showDel = true
          obj.index = this.tableData.length
          this.tableKeys.forEach((item,index)=>{
            obj[item] = ""
          })
          obj.isAdd = true
          this.tableData.push(obj)
        },
        save(row){
          if(row!='SAVEJSON'){
            row.forEach((item,index)=>{
              if(item.isAdd){
                delete item.auto_id
              }
              delete item.isAdd
              delete item.index
              delete item.isEdit
              delete item.showDel
            })
          }
          let v = {
              id:this.selectDataId,
              dataList:row
            }
          if(row=='SAVEJSON'){
            v = this.resultInfo
          }

          request({
            url: '/ht-datadevelop/table/config/saveOrUpdataBatchByTableName',
            method: 'post',
            data: v
          }).then((res) => {
            if(res.code==200){
              this.getIdList()
              this.$message.success("保存成功")
            }else{
              this.$message.error(res.msg)
            }
          })
        },
        tabRowClassName({row,rowIndex}){
            row.index = rowIndex
        },
        editCell(row,column,cell,e){
          if(column.label!='操作'){
            let str = JSON.parse(JSON.stringify(this.tableData))
            str.forEach((item,index)=>{
              item.isEdit = false
            })
            this.$set(row,'isEdit', true)
            str[row.index] = row
            this.tableData = JSON.parse(JSON.stringify(str))
          }
        },
        handleClose(){
          this.$refs.file.clearFiles()
          this.dialogVisible = false
        },
        putInTorage(){},
        getIdList(){
          this.tabLoading = true
          request({
            url: '/ht-datadevelop/table/config/getDataListByTableName',
            method: 'post',
            data: {
              id:this.selectDataId,
              page:this.pageIndex2+"",
              limit:this.pageSize2+""
            }
          }).then((res) => {
            this.tabLoading = false
            if (res.code === 200) {
              this.tableData = res.data.dataInfo.dataList
              this.tableData.forEach((item,index)=>{
                item.isEdit = false
              })
              this.totalPage2 = Number(res.data.dataInfo.dataCount)
              this.tableKeys = res.data.titleList

            } else {
              this.tableData = []
              this.totalPage2 = 0
            }
          })
          setTimeout(()=>{
            this.tabLoading = false
          },60*1000)
        },
        getDetile(v){
          this.selectObj = v
          this.dataObj.tableId = v.id
          this.selectDataId = v.id
          this.getIdList()
          this.dialogVisible = true
        },
        // 获取数据列表
        getDataList (v) {
          if(v==1){
            this.pageIndex = 1
          }
          this.dataListLoading = true
          request({
            url: '/ht-datadevelop/table/config/list',
            method: 'post',
            data:{
              name:this.dataForm.beanName,
              page:this.pageIndex+"",
              limit:this.pageSize+""
            }
          }).then((res) => {
            if (res.code === 200) {
              this.dataList = res.data.list
              this.totalPage = res.data.totalCount
            } else {
              this.dataList = []
              this.totalPage = 0
            }
            this.dataListLoading = false
          })
        },
        // 每页数
        sizeChangeHandle (val) {
          this.pageSize = val
          this.pageIndex = 1
          this.getDataList()
        },
        // 当前页
        currentChangeHandle (val) {
          this.pageIndex = val
          this.getDataList()
        },
         // 每页数
         sizeChangeHandle2 (val) {
          this.pageSize2 = val
          this.pageIndex2 = 1
          this.getIdList()
        },
        // 当前页
        currentChangeHandle2 (val) {
          this.pageIndex2 = val
          this.getIdList()
        },
         // 每页数
         sizeChangeHandle3 (val) {
          this.pageSize3 = val
          this.pageIndex3 = 1
          this.vlogs()
        },
        // 当前页
        currentChangeHandle3 (val) {
          this.pageIndex3 = val
          this.vlogs()
        },
        // 多选
        selectionChangeHandle (val) {
          this.dataListSelections = val
        },
        // 新增 / 修改
        addOrUpdateHandle (row) {
          this.addOrUpdateVisible = true
          this.$nextTick(() => {
            this.$refs.addOrUpdate.init(row)
          })
        },
        // 删除
        deleteHandle (id) {
          var ids = id ? [id] : this.dataListSelections.map(item => {
            return item.id
          })

          // this.$confirm(`确定${id ? '删除' : '批量删除'}?`, '提示', {
          //   confirmButtonText: '确定',
          //   cancelButtonText: '取消',
          //   type: 'warning'
          // }).then(() => {
            request({
              url: '/ht-datadevelop/table/config/deleteByIds',
              method: 'post',
              data:{ids:ids}
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.getDataList()
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          // }).catch(() => {})
        },
      }
    }
  </script>
